<template>
  <div ref="container" class="scene-container"></div>
  <audio
    ref="audio"
    src="/MP3/happybirthday.mp3"
    autoplay
    style="position: fixed; top: 0; left: 0"
    loop
    muted
  ></audio>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import * as THREE from "three";
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls";
import * as dat from "dat.gui";

defineOptions({
  name: "ThreeScene",
});

const container = ref<HTMLElement>();
let scene: THREE.Scene;
let camera: THREE.PerspectiveCamera;
let renderer: THREE.WebGLRenderer;
let controls: OrbitControls;
let sphere: THREE.Mesh;
let plane: THREE.Mesh;
let spotLight: THREE.SpotLight;
let smallBall: THREE.Mesh;
let points: THREE.Points;
let cake: THREE.Mesh; // 添加蛋糕变量
let clock = new THREE.Clock();

const initScene = () => {
  scene = new THREE.Scene();
  scene.background = new THREE.Color(0x000000);

  camera = new THREE.PerspectiveCamera(
    75,
    window.innerWidth / window.innerHeight,
    0.1,
    1000
  );
  camera.position.set(0, 0, 40);
  scene.add(camera);

  // 创建金钱粒子
  const particlesGeometry = new THREE.BufferGeometry();
  const count = 5000;
  const positions = new Float32Array(count * 3);
  const colors = new Float32Array(count * 3);

  for (let i = 0; i < count * 3; i++) {
    positions[i] = (Math.random() - 0.5) * 100;
    colors[i] = Math.random();
  }

  particlesGeometry.setAttribute(
    "position",
    new THREE.BufferAttribute(positions, 3)
  );
  particlesGeometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));

  const textureLoader = new THREE.TextureLoader();
  const moneyTexture = textureLoader.load(
    "/textures/PNG (Black background)/money.png"
  );

  const pointMaterial = new THREE.PointsMaterial({
    size: 1,
    sizeAttenuation: true,
    map: moneyTexture,
    alphaMap: moneyTexture,
    transparent: true,
    depthWrite: false,
    blending: THREE.AdditiveBlending,
    color: 0xffffff,
  });

  pointMaterial.vertexColors = false;
  particlesGeometry.deleteAttribute("uv");
  points = new THREE.Points(particlesGeometry, pointMaterial);
  scene.add(points);

  // 添加蛋糕
  const cakeGeometry = new THREE.PlaneGeometry(10, 10);
  const cakeTexture = textureLoader.load(
    "/textures/PNG (Black background)/cake.png"
  );

  const cakeMaterial = new THREE.MeshBasicMaterial({
    map: cakeTexture,
    // transparent: true,
    side: THREE.DoubleSide,
    depthWrite: false,
    blending: THREE.AdditiveBlending,
  });

  cake = new THREE.Mesh(cakeGeometry, cakeMaterial);
  cake.position.set(0, 0, 0);
  scene.add(cake);

  renderer = new THREE.WebGLRenderer({ antialias: true });
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.PCFSoftShadowMap;
  container.value?.appendChild(renderer.domElement);

  const axesHelper = new THREE.AxesHelper(100);
  // scene.add(axesHelper);

  controls = new OrbitControls(camera, renderer.domElement);
  controls.enableDamping = true;
  controls.dampingFactor = 0.5; //

  // 添加GUI控制
  // const gui = new dat.GUI();
  // const cakeFolder = gui.addFolder("Cake");
  // cakeFolder.add(cake.scale, "x", 0.1, 20).name("宽度");
  // cakeFolder.add(cake.scale, "y", 0.1, 20).name("高度");
  // cakeFolder.add(cake.position, "z", -50, 50).name("深度");
  // cakeFolder.add(cakeMaterial, "opacity", 0, 1).name("透明度");

  animate();
};

const animate = () => {
  let time = clock.getElapsedTime();

  // 金钱粒子动画
  points.rotation.x = time * 0.2;
  points.rotation.y = time * 0.05;

  if (time < 3) {
    // 3秒内完成动画
    // 位置从底部向上移动
    cake.position.y = THREE.MathUtils.lerp(-20, 0, time / 3);

    // 大小从小变大
    const scale = THREE.MathUtils.lerp(0.1, 1, time * 2);
    cake.scale.set(scale, scale, scale);

    // 透明度从0到1
    cake.material.opacity = THREE.MathUtils.lerp(0, 1, time / 3);
  } else {
    // 动画完成后添加浮动效果
    cake.position.y = Math.sin((time - 3) * 2) * 0.5;
  }
  cake.quaternion.copy(camera.quaternion); // 始终面向相机

  requestAnimationFrame(animate);
  controls.update();
  renderer.render(scene, camera);
};

const handleResize = () => {
  if (camera && renderer) {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  }
};
const audio = ref<HTMLAudioElement>();
const isPlaying = ref(false);
const startScene = async () => {
  if (audio.value) {
    try {
      // 检查音频状态
      console.log("音频就绪状态:", audio.value.readyState);
      console.log("音频当前时间:", audio.value.currentTime);
      console.log("音频音量:", audio.value.volume);
      console.log("音频是否静音:", audio.value.muted);

      // 确保不是静音
      audio.value.muted = false;
      // 设置音量
      audio.value.volume = 0.5;

      // 尝试播放
      const playPromise = await audio.value.play();
      isPlaying.value = true;
      console.log("播放成功");

      // 监听播放进度
      audio.value.addEventListener("timeupdate", () => {
        console.log("当前播放时间:", audio.value?.currentTime);
      });
    } catch (error) {
      console.error("播放失败:", error);
      // 如果自动播放失败，等待用户交互
      document.addEventListener(
        "click",
        () => {
          if (audio.value && !isPlaying.value) {
            audio.value
              .play()
              .then(() => {
                isPlaying.value = true;
                console.log("点击后播放成功");
              })
              .catch((err) => console.error("点击后播放失败:", err));
          }
        },
        { once: true }
      );
    }
  }
};

onMounted(() => {
  initScene();
  //隐藏video
  // audio.value.style.display = "none";
  window.addEventListener("resize", handleResize);
  if (audio.value) {
    // 音频事件监听
    audio.value.addEventListener("loadeddata", () => {
      console.log("音频数据加载完成");
    });

    audio.value.addEventListener("canplay", () => {
      console.log("音频可以播放");
    });

    audio.value.addEventListener("play", () => {
      console.log("音频开始播放");
    });

    audio.value.addEventListener("playing", () => {
      console.log("音频正在播放");
    });

    audio.value.addEventListener("pause", () => {
      console.log("音频暂停");
    });

    audio.value.addEventListener("volumechange", () => {
      console.log(
        "音量改变:",
        audio.value?.volume,
        "是否静音:",
        audio.value?.muted
      );
    });

    // 尝试播放
    startScene();
  }

  // 添加点击事件监听
  document.addEventListener("click", () => {
    if (audio.value && !isPlaying.value) {
      startScene();
    }
  });
});

onBeforeUnmount(() => {
  window.removeEventListener("resize", handleResize);
});
</script>

<style scoped>
.scene-container {
  width: 100%;
  height: 100vh;
  overflow: hidden;
}
</style>
